const moment = require('moment')
const mongoose = require('../config/dbHelper')
const Schema = mongoose.Schema

const PostSchema = new Schema({
  uid: { type: String, ref: 'users' },
  title: String,
  content: String,
  created: Date,
  catalog: String,
  fav: String,
  isEnd: String,
  reads: Number,
  answer: Number,
  status: String,
  isTop: String,
  sort: String,
  tags: Array
})

PostSchema.pre('save', function (next) {
  this.created = moment().format('YYYY-MM-DD HH:mm:ss')
  next()
})

PostSchema.statics = {
  /**
   * 文章列表
   * @param {*} options 筛选条件
   * @param {*} sort 排序方式
   * @param {*} page 分页页数
   * @param {*} limit 分页条数
   */
  getList (options, sort, page, limit) {
    return this.find(options)
      .sort({ [sort]: -1 })
      .skip(page * limit)
      .limit(limit)
      .populate({
        path: 'uid',
        select: ['name', 'pic', 'isVip']
      })
  },
  getTopWeek () {
    return this.find({
      created: {
        $gte: moment().subtract(7, 'days')
      }
    }, {
      answer: 1,
      title: 1
    }).sort({
      answer: -1
    }).limit(15)
  }
}

const PostModel = mongoose.model('post', PostSchema)
module.exports = PostModel
